from case.models import Case, CustomerCase
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from users.models import UserInfo
from wxchat.api.permissions import WeixinPermission
from case.api.wechat_serializers import WxCaseSerializer, CustomerCaseSerializer
from wxchat.utils import get_openid_from_header


class WxCaseViewSet(ModelViewSet):
    permission_classes = ()
    queryset = Case.objects.all()
    serializer_class = WxCaseSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = self.request.user
        if not isinstance(user, UserInfo):
            return None

        if not user.is_superuser:
            count = user.roles.filter(only_own=True).count()
            if count > 0:
                queryset = queryset.filter(Q(lead_lawyer=user) | Q(assist_lawyer=user) | Q(third_lawyer=user) | Q(user=user))

        case_type = self.request.query_params.get("case_type", None)
        key_word = self.request.query_params.get("key_word", None)
        archive_flag = self.request.query_params.get("archive_flag", None)
        print("archive_flag:", archive_flag)
        # 查看详细内容
        if self.lookup_field in self.kwargs:
            return queryset

        if archive_flag == "1":
            queryset = queryset.filter(archive_flag=True)
        else:
            queryset = queryset.filter(archive_flag=False)

        if case_type:
            queryset = queryset.filter(case_type=case_type)

        if key_word:
            queryset = queryset.filter(
                Q(reason__contains=key_word) | Q(party__contains=key_word)
                | Q(client__contains=key_word) | Q(client__contains=key_word)
                | Q(lead_lawyer__real_name__contains=key_word)
            )

        return queryset


class WxCaseClientViewSet(ReadOnlyModelViewSet):
    """
    客户案件
    """
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    queryset = Case.objects.all()
    serializer_class = WxCaseSerializer

    def get_queryset(self):

        queryset = super().get_queryset()

        openid = get_openid_from_header(self.request)

        if openid:
            queryset = queryset.filter(customers__openid=openid)

            key_word = self.request.query_params.get("key_word", None)
            archive_flag = self.request.query_params.get("archive_flag", None)

            if archive_flag == "1":
                queryset = queryset.filter(archive_flag=True)
            else:
                queryset = queryset.filter(archive_flag=False)

            if key_word:
                queryset = queryset.filter(
                    Q(reason__contains=key_word) | Q(party__contains=key_word)
                    | Q(client__contains=key_word) | Q(client__contains=key_word)
                    | Q(lead_lawyer__real_name__contains=key_word)
                )

        else:
            queryset = None

        return queryset


class WxCustomerCaseViewSet(ModelViewSet):
    """
    客户案件
    """
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = CustomerCase.objects.all()
    serializer_class = CustomerCaseSerializer

    def get_queryset(self):

        queryset = super().get_queryset()
        openid = get_openid_from_header(self.request)

        if openid:
            queryset = queryset.filter(openid=openid)
        else:
            queryset = None

        return queryset

    @action(methods=["put"], detail=False)
    def authorize(self, request, *args, **kwargs):
        case_id = request.data.get("case_id", None)
        openid = get_openid_from_header(self.request)

        if not case_id or not openid:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "授权失败!"}
            return Response(data=msg, status=status.HTTP_200_OK)

        defaults = dict()

        obj, created = self.serializer_class.Meta.model.objects.update_or_create(defaults=defaults, case_id=case_id, openid=openid)
        if obj:
            if created:
                msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "授权成功!"}
                return Response(data=msg, status=status.HTTP_200_OK)
            else:
                msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "已经授权, 无须再次授权"}
                return Response(data=msg, status=status.HTTP_200_OK)
        else:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "授权失败!!"}
            return Response(data=msg, status=status.HTTP_200_OK)




